<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.serialNumber" size="medium" clearable placeholder="门锁编号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.model" size="medium" clearable placeholder="型号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button class="filter-item" size="medium" style="margin-left: 20px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <!--超级管理员不能操作设备-->
      <div v-if="!isSuperAdmin" style="display: inline-block">
        <el-button class="filter-item" type="warning" size="medium" style="margin-left: 50px;" @click="handleCreate">添加门锁</el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row>
      <el-table-column label="门锁编号" width="150">
        <template slot-scope="scope">
          <span class="link-type" @click="$router.push({ name: 'LockDetail', params: { 'sn': scope.row.serialNumber, 'id': scope.row.id }})">{{ scope.row.serialNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="型号">
        <template slot-scope="scope">
          {{ scope.row.model }}
        </template>
      </el-table-column>
      <el-table-column label="安装位置" width="200">
        <template slot-scope="scope">
          {{ scope.row.address }}
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <!--超级管理员不能操作设备-->
      <el-table-column v-if="!isSuperAdmin" label="操作" width="200">
        <!--授权管理员不能操作设备-->
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <el-button size="mini" icon="el-icon-edit" type="primary" circle @click="handleEdit(scope.row)"/>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="离线授权" placement="top">
            <el-button size="mini" type="warning" circle @click="handleAuth(scope.row)"><svg-icon icon-class="verifycode"/></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button size="mini " icon="el-icon-delete" type="danger" circle @click="handleDelete([scope.row.id])"/>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column v-else label="管理员">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
    </el-table>
    <div v-if="list.length > 0" class="pagination-container">
      <el-pagination :current-page="listQuery.currentPage" :page-sizes="[10,25,50,100]" :page-size="listQuery.pageSize" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>

    <!--门锁表单-->
    <el-dialog :visible.sync="dialogFormVisible" :title="isEdit ? '编辑门锁' : '添加门锁'" center width="40%">
      <el-form ref="dataForm" :label-width="formLabelWidth" :rules="rules" :model="form">
        <device-form v-if="dialogFormVisible" :form="form" :is-edit="isEdit" :form-label-width="formLabelWidth" sn-title="门锁编号"/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!--离线授权表单-->
    <el-dialog :visible.sync="dialogForm2Visible" title="添加授权" center width="40%">
      <el-form ref="dataForm2" :label-width="formLabelWidth" :rules="rules2" :model="form2">
        <el-form-item label="生效时段" prop="duration">
          <el-date-picker
            v-model="form2.startTime"
            :default-value="currentTime"
            type="datetime"
            value-format="timestamp"
            placeholder="开始时间"/>
          ~
          <el-date-picker
            v-model="form2.endTime"
            :default-value="form2.startTime"
            type="datetime"
            value-format="timestamp"
            placeholder="结束时间"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm2Visible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm2">确 定</el-button>
      </div>
    </el-dialog>

    <back-to-top :custom-style="myBackToTopStyle" :visibility-height="10" :back-position="0" transition-name="fade"/>
  </div>
</template>

<script>
import { getDevices, addDevices, deleteDevices, editDevice, addKey } from '@/api/device'
import BackToTop from '@/components/BackToTop'
import DeviceForm from '@/components/DeviceForm'
import { mapGetters } from 'vuex'

export default {
  name: 'Smartlock',
  components: { BackToTop, DeviceForm },
  data() {
    /* 校验生效时段 */
    const validateDuration = (rule, value, callback) => {
      if (!this.form2.startTime) {
        callback(new Error('请选择开始时间'))
      } else if (!this.form2.endTime) {
        callback(new Error('请选择结束时间'))
      } else {
        callback()
      }
    }
    return {
      currentTime: new Date().getTime(),
      list: [],
      total: 0,
      listLoading: true,
      isEdit: false,
      editId: null,
      listQuery: {
        currentPage: 1,
        pageSize: 25,
        deviceType: 1, /* 1-门锁 */
        serialNumber: '',
        model: ''
      },
      dialogFormVisible: false,
      form: { /* 添加、编辑门锁表单 */
        serialNumber: '',
        deviceType: 1,
        regCode: '',
        address: '',
        description: ''
      },
      rules: {
        serialNumber: [{ required: true, message: '请输入门锁编号', trigger: 'blur' }],
        regCode: [{ required: true, message: '请输入校验码', trigger: 'blur' }]
      },
      dialogForm2Visible: false,
      form2: { /* 添加离线授权 */
        id: '',
        serialNumber: '',
        startTime: null,
        endTime: null
      },
      rules2: {
        duration: [{ validator: validateDuration, trigger: 'change' }]
      },
      formLabelWidth: '100px',
      myBackToTopStyle: {
        right: '50px',
        bottom: '50px',
        width: '40px',
        height: '40px',
        'border-radius': '4px',
        'line-height': '45px',
        background: '#e7eaf1'
      }
    }
  },
  computed: {
    ...mapGetters([
      'isSuperAdmin'
    ])
  },
  created() {
    this.fetchData()
  },
  methods: {
    /* 获取设备列表 */
    fetchData() {
      this.listLoading = true
      getDevices(this.listQuery).then(response => {
        if (response.data) {
          this.list = response.data
          this.total = response.total
        }
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.currentPage = 1
      this.fetchData()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.currentPage = val
      this.fetchData()
    },
    resetForm() {
      this.form = {
        serialNumber: '',
        regCode: '',
        deviceType: 1,
        address: '',
        description: ''
      }
    },
    /* 添加门锁 */
    handleCreate() {
      this.isEdit = false
      this.resetForm()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /* 修改门锁信息 */
    handleEdit(row) {
      this.isEdit = true
      this.editId = row.id
      this.form.serialNumber = row.serialNumber
      this.form.address = row.address
      this.form.description = row.description
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /* 提交门锁表单 */
    submitForm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            editDevice(this.editId, this.form).then(() => {
              this.actiniaSucc('编辑门锁成功')
              this.dialogFormVisible = false
              this.fetchData()
            })
          } else {
            addDevices([this.form]).then(() => {
              this.actiniaSucc('添加门锁成功')
              this.dialogFormVisible = false
              this.fetchData()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    /* 删除门锁 */
    handleDelete(arr) {
      this.$confirm('删除门锁您将失去对该门锁的管理权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDevices(arr).then(() => {
          this.actiniaSucc('删除门锁成功')
          this.fetchData()
        })
      }).catch(() => {
        console.log('cancel delete')
      })
    },
    resetForm2() {
      this.form2 = {
        id: '',
        serialNumber: '',
        startTime: null,
        endTime: null
      }
    },
    handleAuth(row) {
      this.resetForm2()
      this.form2.id = row.id
      this.form2.serialNumber = row.serialNumber
      this.dialogForm2Visible = true
      this.$nextTick(() => {
        this.$refs['dataForm2'].clearValidate()
      })
    },
    /* 提交离线授权表单 */
    submitForm2() {
      this.$refs['dataForm2'].validate((valid) => {
        if (valid) {
          addKey(this.form2).then(() => {
            this.actiniaSucc('添加授权成功')
            this.dialogForm2Visible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .alert {
    color: #F56C6C
  }
  .normal {
    color: #67C23A
  }
  .transform-90 {
    transform:rotate(90deg);
    -ms-transform:rotate(90deg); /* Internet Explorer */
    -moz-transform:rotate(90deg); /* Firefox */
    -webkit-transform:rotate(90deg); /* Safari 和 Chrome */
    -o-transform:rotate(90deg); /* Opera */
  }
</style>
